from django import template
from django.template.loader import render_to_string
from django.contrib.contenttypes.models import ContentType 
from ..models import Image

register = template.Library()


class RenderHiddenVarNode(template.Node):
    def __init__(self, objname):
        self.objname = objname

    def render(self, context):
        tokens = self.objname.split('.')
        if len(tokens) == 1:
            obj = context[self.objname]
        else:
            tmp = context[tokens[0]]
            for k in tokens[1:]:
                tmp = hasattr(tmp, 'get') and tmp.get(k, None) or getattr(tmp, k)
            obj = tmp

        obj_type = ContentType.objects.get_for_model(obj)
        return render_to_string("upload/hidden.html", {"objid":obj.id, "ctypeid":obj_type.id}, context) 


def do_render_hiddenvar(parser, token):
    """
    Syntax:: {% render_album for [object] %}
    """
    tokens = token.contents.split()
    if tokens[1] != 'for':
        raise template.TemplateSyntaxError("Second argument in %r tag must be 'for'" % tokens[0])

    if len(tokens) != 3:
        raise template.TemplateSyntaxError("%s require to argument" % tokens[0])

    return RenderHiddenVarNode(tokens[2])    


register.tag('upload', do_render_hiddenvar)



